"use strict"
/// <reference path="../../index.d.ts" />
const Controller = require("egg").Controller
const {sendStat} = require("../extend/helper")
const path = require("path")
const fs = require("fs")
class ShareInfoController extends Controller {
	constructor(ctx) {
		super(ctx)
		this.constant = this.config.constant
		this.serverConfig = this.config.serverConfig
		this.ShareInfo = this.app.model.ShareInfo
		this.uploadPath = this.app.config.serverConfig.uploadPath
		this.imgBase = this.config.serverConfig.imgBase
	}
	async getShareInfo() {// pre 
		let aid = this.ctx.wechat.aid
		let shareInfos = await this.ShareInfo.findAll({
			where: {
				aid
			},
			raw: true
		})
		this.ctx.body = sendStat(this.constant.NORMAL, shareInfos)
	}
	async addOrModShareInfo() {// query 
		let ctx = this.ctx
		let body = Object.assign({}, this.ctx.req.body)
		let queryData = {}
		this.ctx.validate({
			remarks: {
				allowEmpty: true,
				type: "string"
			}, key: "string",
			stat: "numstr",
			title: "string",
			attr: "string",
			desc: {
				allowEmpty: true,
				type: "string"
			},
			edit: ["0", "1"]
		}, body)
		body.edit == Number(body.edit)

		let fileObj = {}
		this.ctx.req.files.forEach((val) => {
			fileObj[val.fieldname] = val
		})
		let uploadStat = true
		if (!Array.isArray(ctx.req.files) || ctx.req.files.length != 1 || fileObj.image_url == undefined) {
			let e = new Error()
			uploadStat = false
			Object.assign(e, {"message": "创建时候必须上传图片", "field": "image_url", "code": "missing_file"})
			if (body.edit == 0)// 创建时候没有上传图片不允许
				ctx.throw(422, "no has file", {
					code: "invalid_param",
					errors: [e],
				})
		}
		if (body.edit == 1) {
			queryData.id = body.id
		}
		if (uploadStat) {
			let fileName = fileObj.image_url.filename + "." + fileObj.image_url.mimetype.split("/").pop()
			let mvPath = path.resolve(path.join(this.uploadPath, fileName))
			fs.renameSync(fileObj.image_url.path, mvPath)
			queryData.image_url = this.imgBase + fileName
		}

		let s = await this.ShareInfo.upsert({
			aid: this.ctx.wechat.aid,
			title: body.title,
			stat: body.stat,
			remarks: body.remarks,
			desc: body.desc,
			attr: body.attr,
			key: body.key,
			...queryData
		}, {
			fields: ["title", "stat", "remarks", "desc", "key", "image_url", "attr"]
		})

		if (s || body.edit == 1) {
			this.ctx.body = sendStat(this.constant.NORMAL)
		} else {
			this.ctx.body = sendStat(this.constant.ERROR_SQL_CREATE)
		}
	}
}
module.exports = ShareInfoController